clear;clc;
%% create session, connect devices
session=MeasurementSession.SimpleMeasurement('./device.dat');
% session.getAllDevicesInBase('session');

%% add parameters
session.addParameter('CellTemperature', 90.9, 'degreeC');
session.addParameter('PumpControlVolt', 1.0, 'V');
session.addParameter('ProbPower', 2.0, 'mW');
session.addParameter('MainFieldControl', 3.0, 'V');
session.addParameter('ZFieldBiasControl', 4.5, 'V');
session.addParameter('RFOffset', 0.5, 'V');
session.addParameter('RFAmplitude', 0.030, 'V');

%% Device Settings

% sweeper
sweeper = session.getDevice('dev3543').sweepModule();
sweeper.setControl('xmapping', 1, 'start', 10e3, 'stop', 80e3)...
       .setFilter('bandwidthcontrol', 0)...
       .setSettling('settling_tc', 1)...
       .setStatistics('averaging_sample', 100)...
       .setOption()...
       .showParam();

% aom: Pump power
aom = session.getDevice('aomPump');
aom.setDC( session.getParameter('PumpControlVolt') ).fire();

% zi: magnetic field control
zi = session.getDevice('dev3543');
zi.setAuxOutOffset('0', session.getParameter('MainFieldControl') ) ...
  .setAuxOutOffset('1', session.getParameter('ZFieldBiasControl') )...
  .setSigOutOffset( session.getParameter('RFOffset') ) ...
  .setSigOutAmplitude('0', session.getParameter('RFAmplitude') ) ...
  .fireSigOut();

%% Batch Sweep
session.addParameter('scanTopticaVolt', 80:0.1:95, 'V');
session.makeLoopIndex('scanTopticaVolt');

sweeper.subscribeChannel('0');
result = sweeper.batchSweep_Session(@batch_fun, session);
sweeper.unsubscribeChannel('0');

%% save results
session.addMeasurementData(result);
MeasurementSession.save(session);

%% Operations of Each Sweep
function res = batch_fun(sweeper, index, session, varargin)
    %  get Parameters
    p=inputParser;
    isSwpr = @(x) isa(x, 'EquipmentControl.AnalyseEquipment.ZI.ziSweeper');
    isSess = @(x) isa(x, 'MeasurementSession.AbstractMeasurementSession');
    
    p.addRequired('sweeper', isSwpr );
    p.addRequired('index', @isnumeric);
    p.addRequired('session',  isSess);
    p.parse(sweeper, index, session, varargin{:});

    swpr = p.Results.sweeper;
    idx = p.Results.index;
    sess = p.Results.session;
    
    %  change settings (e.g., laser voltage) for each parameter sweeping.
    laser = sess.getDevice('toptica64');
    scanVolt = sess.getParameter('scanTopticaVolt');
    laser.disableScan().setScanOffsetVolt( scanVolt(idx) );
    fprintf('\t Sweeping at paramter: %f ... \n', scanVolt(idx));
    pause(5);

    % do the sweep
    res = swpr.run('index', idx, 'silence', 0);
end
